<?php
//include_once(dirname(__FILE__)."/AlbumClass.php");
//include_once(dirname(__FILE__)."/Zphoto.php");
/**
 * Lớp luân chuyển giữa csdl và object
 * Lớp gắn với bẳng pl_gp_review trong csdl 
 * @author nhat
 *
 */
class Zreview extends ObjectModel {
	/*Khai báo tất cả các trường*/
	public $id;
	public $id_zgallery_review;
	public $id_zgallery_photo;
	public $id_customer;
	public $ip_client;
	public $active=1;
	public $date_add;
	public $content;
	public $nickname;
	public $email;
	public $table = 'zgallery_review';
	protected $identifier = 'id_zgallery_review';
	/*Xác định các trường nào phải bắt buộc phải có*/ 
	protected	$fieldsRequired = array('nickname', 'email', 'rate');
	protected	$fieldsValidate = array('nickname' => 'isName', 'email' => 'isEmail');
	/*Xác định kích thước tối đa cho trường*/
	protected 	$fieldsSize = array('nickname' => 249,'email'=>249);
	protected   $fieldsValidateLang = array('content' => 'isString');
	protected   $url;
	protected   $allow;
	/**
	 * Lấy các thông tin từ trường
	 */
	public function getFields ()
	{
		parent::validateFields ();
		$fields['id_zgallery_review']=(int)($this->id);
		$fields['id_customer']=pSQL($this->id_customer);
		$fields['ip_client']=pSQL($this->ip_client);
		$fields['id_zgallery_photo']=pSQL($this->id_zgallery_photo);
		$fields['active']=pSQL($this->active);
		$fields['date_add']=pSQL($this->date_add);
		$fields['nickname']=pSQL($this->nickname);
		$fields['email']=pSQL($this->email);
		return $fields;
	}
	
	/**
	* Check then return multilingual fields for database interaction
	*
	* @return array Multilingual fields
	*/
	
	public function getTranslationsFieldsChild()
	{
		$fieldsArray = array('content');
		$fields = array();
		$languages = Language::getLanguages(false);
		$defaultLanguage = Configuration::get('PS_LANG_DEFAULT');
		foreach ($languages as $language)
		{
			$fields[$language['id_lang']]['id_lang'] = $language['id_lang'];
			$fields[$language['id_lang']][$this->identifier] = (int)($this->id);
			foreach ($fieldsArray as $field)
			{
				if (!Validate::isTableOrIdentifier($field))
					die(Tools::displayError());
				
				/* Check fields validity */
				if (isset($this->{$field}[$language['id_lang']]) AND !empty($this->{$field}[$language['id_lang']])) {
					$fields[$language['id_lang']][$field] = pSQL($this->{$field}[$language['id_lang']], true);					
				}
				elseif (in_array($field, $this->fieldsRequiredLang))
					$fields[$language['id_lang']][$field] = pSQL($this->{$field}[$defaultLanguage]);
				else
					$fields[$language['id_lang']][$field] = '';		
			}
		}
		return $fields;
	}
	/**
	 * Chuyển giữa multilang
	 * @param unknown_type $fields
	 * @param unknown_type $fieldsArray
	 * @param unknown_type $id_language
	 */
	protected function makeTranslationFields(&$fields, &$fieldsArray, $id_language)
	{
		$fields[$id_language]['id_lang'] = $id_language;
		$fields[$id_language][$this->identifier] = (int)($this->id);
		foreach ($fieldsArray as $field)
		{
			/* Check fields validity */
			if (!Validate::isTableOrIdentifier($field))
				die(Tools::displayError());

			/* Copy the field, or the default language field if it's both required and empty */
			if ((!$this->id_lang AND isset($this->{$field}[$id_language]) AND !empty($this->{$field}[$id_language])) 
			OR ($this->id_lang AND isset($this->$field) AND !empty($this->$field)))
				$fields[$id_language][$field] = $this->id_lang ? pSQL($this->$field,true) : pSQL($this->{$field}[$id_language],true);
			elseif (in_array($field, $this->fieldsRequiredLang))
				$fields[$id_language][$field] = $this->id_lang ? pSQL($this->$field,true) : pSQL($this->{$field}[Configuration::get('PS_LANG_DEFAULT')],true);
			else
				$fields[$id_language][$field] = '';
		}
	}
	/**
	 * Hàm dựng
	 * khai báo cho phép rewrite
	 * lấy địa chỉ url
	 * @param unknown_type $id
	 * @param unknown_type $id_lang
	 */
	public function __construct($id=NULL,$id_lang=NULL){
		$this->allow = (int)Configuration::get('PS_REWRITING_SETTINGS');
		$this->url = $_SERVER['SCRIPT_NAME'];
		parent::__construct($id, $id_lang);
	}
	/**
	 * copy từ post sang object
	 */
	public function copyFromPost()
	{
		/* Classical fields */
		foreach ($_POST AS $key => $value)
			if (key_exists($key, $this) AND $key != 'id_'.$this->table)
				$this->{$key} = $value;
		foreach ($_GET AS $key => $value)
			if (key_exists($key, $this) AND $key != 'id_'.$this->table)
				$this->{$key} = $value;
		
		foreach ($this->fieldsValidateLang AS $key => $value)	{
			$languages = Language::getLanguages(false);
			foreach ($languages AS $language) {
				if (isset($_POST[$key.'_'.(int)($language['id_lang'])])) {
					$this->{$key}[(int)($language['id_lang'])] = $_POST[$key.'_'.(int)($language['id_lang'])];
				}
			}
		}
	}
	
	/**
	 * Tạo Icon mới ở bên nút active
	 * @param unknown_type $id_zgallery_review
	 * @param unknown_type $tr
	 */
	static public function printNewsIconStatus($id_zgallery_review, $tr)
	{
		$ReviewClass = new Zreview ($tr['id_zgallery_review']);
		echo 
		'<a href="index.php?tab=AdminPlGalleryPro&id_zgallery_review='.(int)($ReviewClass->id).'&changeStatus&token='.Tools::getAdminTokenLite('AdminPlGalleryPro').'">
			'.($ReviewClass->active==1 ? '<img src="../img/admin/enabled.gif" />' : ( $ReviewClass->active==0?'<img src="../img/admin/disabled.gif" />':'<img src="../img/admin/forbbiden.gif" />')).'
		</a>
		';	
	}
	/**
	 * Get list reviews for product
	 * 
	 * @param int $id_product	product id
	 * @param int $p			current page
	 * @param int $n			number items display in page
	 */
	static public function getListReviews ($id_zgallery_photo, $p=1, $n=10,$id_lang) {
		$query= '
		SELECT *
			FROM `'._DB_PREFIX_.'zgallery_review` a 
			LEFT JOIN `'._DB_PREFIX_.'zgallery_review_lang` rl ON (a.`id_zgallery_review` = rl.`id_zgallery_review` and rl.`id_lang`='.$id_lang.')
			WHERE `active`=1
			ORDER BY `date_add` DESC 
			'.($n ? 'LIMIT '.(int)(($p - 1) * $n).', '.(int)($n) : '')
		;
		$results = Db::getInstance()->ExecuteS($query);
		foreach ($results as $key=>$result) {
			$results[$key]['link'] = Zalbum::getAlbumCurrent ($result['id_zgallery_photo']);
			$results[$key]['nameAlbum'] = Zalbum::getNameAlbum ($result['id_zgallery_photo'],$id_lang);
		}
		return $results;
	}
	/**
	 * Số Review cho photo
	 * @param unknown_type $id_zgallery_photo
	 */
	static public function getNumberReviews ($id_zgallery_photo){
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT COUNT(`id_zgallery_review`) AS "nbr"
			FROM `'._DB_PREFIX_.'zgallery_review`
			WHERE  `active`=1');
		return (int)($result['nbr']);
	}
	/**
	 * Lấy ra comment của 1 ip ở photo
	 * @param $id_zgallery_photo
	 * @param $ip_client
	 * @param $id_customer
	 */
	static public function customerComment ($id_zgallery_photo,$ip_client,$id_customer=false)
	{
		$query='
		SELECT * 
			FROM `'._DB_PREFIX_.'zgallery_review` pc
			WHERE pc.`id_zgallery_photo` = '.(int)($id_zgallery_photo).' AND 
				'.($id_customer ? 'pc.`id_customer` = '.(int)($id_customer) : 'pc.`ip_client` = "'.($ip_client).'"').'
			ORDER BY pc.`date_add` DESC 
		';
		return Db::getInstance()->getRow($query);
	}
	/**
	 * get code html 
	 * @param $id
	 */
	static function getHtmlLiListComment ($id,$p,$n,$id_lang) {
		$listComment = Zreview::getListReviews($id,$p,$n,$id_lang);
		$nb = Zreview::getNumberReviews($id);
		$html='';
		for ($i = sizeof($listComment)-1; $i >=0 ; $i--) {
			$html.= '
				<li class="zitemComment">	
					<div class="zcommentContent">
						<a href="'.$listComment[$i]['link'].'">
							<p>'.substr($listComment[$i]['nameAlbum'],0,30).''.(strlen($listComment[$i]['nameAlbum'])>30?'...':'').'</p>
						</a>
						<b>'.$listComment[$i]['nickname'].'</b> 
						<span class="zcommentBody">'.$listComment[$i]['content'].'</span>
						<div class="zcommentActions">
							<b>'.$listComment[$i]['date_add'].'</b>
						</div>
					</div>
				</li>
			';
		}
		return $html;		
	} 
	public function getRate ($id) {
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT SUM(rate) as rs, COUNT(id_zgallery_review)as nb FROM '._DB_PREFIX_.'zgallery_review 
			WHERE id_zgallery_photo='.$id.' AND active=1');
		return (int)($result['rs']/($result['nb']==0?1:$result['nb']));
	}
	/**
	 * Lấy link Url photo
	 * @param unknown_type $i
	 * @param unknown_type $v
	 */
	public  function getLinkUrlPhoto ($i=null,$v=null) {
		global $cookie,$link;
		$linkHome = $link->getPageLink('');
		
		if ($i==NULL)
			if ( isset($_GET['i'])==0 ) {
				$i=1;
			}
			else $i=$_GET['i'];
		if ($v==NULL) {
			if ( isset($_GET['v'])==0 ) {
				$v=1;
			}
			else $v=$_GET['v'];
		}
		$frl = Zreview::getParentsAlbum ($i);
		$frl=$frl['freurl'];
		$out = $linkHome."photo-gallery";
		$out.='/'.$i.'_'."$frl";
		$frl = Zreview::getPhotoCurrent($v) ;
		$frl=$frl['freurl'];
		$out.='/'.$v.'_'."$frl";
		return $out;
	}
	/**
	 * Lấy ra album cha của album id
	 * @param unknown_type $id
	 */
	public function getParentsAlbum ($id) {
		global $cookie;
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT * FROM '._DB_PREFIX_.'zgallery_album a
			LEFT JOIN '._DB_PREFIX_.'zgallery_album_lang b ON (a.id_zgallery_album=b.id_zgallery_album AND b.id_lang='.$cookie->id_lang.')
			WHERE a.id_zgallery_album='.$id.' 
		');
		return $result;
	}
	
	/**
	 * Lấy ra thông tin về photo với địa chỉ id
	 * @param unknown_type $id
	 */
	public function getPhotoCurrent ($id) {
		global $cookie;
		$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
			SELECT * FROM '._DB_PREFIX_.'zgallery_photo a
			LEFT JOIN '._DB_PREFIX_.'zgallery_photo_lang b ON (a.id_zgallery_photo=b.id_zgallery_photo)
			WHERE a.id_zgallery_photo='.$id.' AND b.id_lang='.$cookie->id_lang.'
		');
		return $result;
	}
	
	/** 
	 * đi tới page có thể xem thêm ở class Link
	 * @param unknown_type $url
	 * @param unknown_type $p
	 */
	public function goPage($url, $p)
	{
		return $url.($p == 1 ? '' : (!strstr($url, '?') ? '?' : '&amp;').'p='.(int)($p));
	}
	/**
	 * Đi tới 1 link
	 * có thể xem thêm ở class Link
	 * @param unknown_type $url
	 * @param unknown_type $p
	 */
	public function goLink($url, $p)
	{
		return $url.($p == 1 ? '' : (!strstr($url, '?') ? '?' : '&amp;').'mode='.(int)($p));
	}
	/**
	 * Đặt link cho một trang 
	 * có thể xem thêm ở class Link 
	 * @param unknown_type $filename
	 * @param unknown_type $ssl
	 * @param unknown_type $id_lang
	 */
	public function getPageLink($filename, $ssl = false, $id_lang = NULL)
	{
		global $cookie,$cache;
		if ($id_lang == NULL)
			$id_lang = (int)($cookie->id_lang);

		if ($this->allow == 1)
		{
			$url_rewrite = '';
			if ($filename != 'index.php')
			{
				$pagename = substr($filename, 0, -4);
				$url_rewrite = Db::getInstance()->getValue('
				SELECT url_rewrite
				FROM `'._DB_PREFIX_.'meta` m
				LEFT JOIN `'._DB_PREFIX_.'meta_lang` ml ON (m.id_meta = ml.id_meta)
				WHERE id_lang = '.(int)($id_lang).' AND `page` = \''.pSQL($pagename).'\'');
				$uri_path = $this->getLangLink((int)$id_lang).($url_rewrite ? $url_rewrite : $filename);
			}
			else
				$uri_path = $this->getLangLink((int)$id_lang);
		}
		else
		{
			$uri_path = '';
			if ($filename != 'index.php')
				$uri_path = $filename;
		}
	
		return (($ssl AND Configuration::get('PS_SSL_ENABLED')) ? Tools::getShopDomainSsl(true) : Tools::getShopDomain(true)).__PS_BASE_URI__.ltrim($uri_path, '/');
	}
	/**
	 * Lấy ra link phân trang
	 * @param unknown_type $type
	 * @param unknown_type $id_object
	 * @param unknown_type $nb
	 * @param unknown_type $sort
	 * @param unknown_type $pagination
	 * @param unknown_type $array
	 */
	public function getPaginationLink($type, $id_object, $nb = false, $sort = false, $pagination = false, $array = false)
	{
		global $cookie,$link;
		$linkHome = $link->getPageLink('');
		if ($type AND $id_object)
			$url = $this->{'get'.$type.'Link'}($id_object, NULL);
		else
		{
			$url = $this->url;
			if (Configuration::get('PS_REWRITING_SETTINGS'))
				$url = $this->getLinkUrlPhoto();
		}
		$vars = (!$array ? '' : array());
		$varsNb = array('n', 'search_query');
		$varsSort = array('orderby', 'orderway');
		$varsPagination = array('p');

		$n = 0;
		foreach ($_GET AS $k => $value)
			if ($k != 'id_'.$type)
			{
				if (Configuration::get('PS_REWRITING_SETTINGS') AND ($k == 'isolang' OR $k == 'id_lang' OR $k='i' OR $k='v' OR $k == '_php?isolang'))
					continue;
				$ifNb = (!$nb OR ($nb AND !in_array($k, $varsNb)));
				$ifSort = (!$sort OR ($sort AND !in_array($k, $varsSort)));
				$ifPagination = (!$pagination OR ($pagination AND !in_array($k, $varsPagination)));
				if ($ifNb AND $ifSort AND $ifPagination AND !is_array($value))
					!$array ? ($vars .= ((!$n++ AND ($this->allow == 1 OR $url == $this->url)) ? '?' : '&').urlencode($k).'='.urlencode($value)) : ($vars[urlencode($k)] = urlencode($value));
			}
		if (!$array)
			return $url.$vars;
		
		$vars['requestUrl'] = $url;
		if ($type AND $id_object)
			$vars['id_'.$type] = (is_object($id_object) ? (int)$id_object->id : (int)$id_object);
		return $vars;
	}
	/**
	 * Lấy link từ csdl
	 * @param unknown_type $type
	 * @param unknown_type $id_object
	 * @param unknown_type $nb
	 * @param unknown_type $sort
	 * @param unknown_type $pagination
	 * @param unknown_type $array
	 */
	public function getLink($type, $id_object, $nb = false, $sort = false, $pagination = false, $array = false)
	{
		global $cookie,$link;
		$linkHome = $link->getPageLink('');
		
		if ($type AND $id_object)
			$url = $this->{'get'.$type.'Link'}($id_object, NULL);
		else
		{
			$url = $this->url;
			if (Configuration::get('PS_REWRITING_SETTINGS')) {
				$url = $this->getLinkUrlPhoto();
			}
		}
		$vars = (!$array ? '' : array());
		$varsNb = array('mode', 'search_query');
		$varsSort = array('orderby', 'orderway');
		$varsPagination = array('mode');

		$n = 0;
		foreach ($_GET AS $k => $value)
			if ($k != 'id_'.$type)
			{
				if (Configuration::get('PS_REWRITING_SETTINGS') AND ($k == 'isolang' OR $k == 'id_lang' OR $k='i' OR $k='v'))
					continue;
				$ifNb = (!$nb OR ($nb AND !in_array($k, $varsNb)));
				$ifSort = (!$sort OR ($sort AND !in_array($k, $varsSort)));
				$ifPagination = (!$pagination OR ($pagination AND !in_array($k, $varsPagination)));
				if ($ifNb AND $ifSort AND $ifPagination AND !is_array($value))
					!$array ? ($vars .= ((!$n++ AND ($this->allow == 1 OR $url == $this->url)) ? '?' : '&').urlencode($k).'='.urlencode($value)) : ($vars[urlencode($k)] = urlencode($value));
			}
		if (!$array)
			return $url.$vars;
		$vars['requestUrl'] = $url;
		if ($type AND $id_object)
			$vars['id_'.$type] = (is_object($id_object) ? (int)$id_object->id : (int)$id_object);
		return $vars;
	}
}
